<template>
    <div class="tags" v-if="showTags">
        <ul>
            <li class="tags-li" v-for="(item,index) in tagsList" :key="index" :class="{'active': isActive(item.path)}">
                <router-link :to="item.path" class="tags-li-title">
                    {{item.title}}
                </router-link>
                <span class="tags-li-icon" @click="closeTags(index)"><i class="el-icon-close"></i></span>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
  name: "HomeTags",
  data() {
    return {
      tagsList: []
    };
  },
  methods: {
    // 设置标签状态
    isActive(path) {
      // 如果标签的路径与当前路由路径相同则为选中状态
      return path === this.$route.fullPath;
    },
    // 关闭标签
    closeTags(index) {
      let delItem = this.tagsList.splice(index, 1)[0];
      let item = this.tagsList[index - 1];
      if (item) {
        // 如果删除的标签是当前路由则把路由跳到前一个路由
        if (delItem.path === this.$route.fullPath) {
          this.$router.push(item.path);
        }
      } else {
        this.$router.push("/home/index");
      }
    },
    setTags(route) {
      // some检测数组是否有等于 route.fullPath 的值
      let isExist = this.tagsList.some(item => {
        return item.path === route.fullPath;
      });
      if (!isExist) {
        this.tagsList.push({
          title: route.meta.title,
          path: route.fullPath
        });
      }
    }
  },
  //检查路由变化
  watch: {
    $route(newValue, oldValue) {
      this.setTags(newValue);
    }
  },
  computed: {
    //标签是否显示
    showTags() {
      return this.tagsList.length > 0;
    }
  },
  created() {
    //   console.log(this.$route);
    this.setTags(this.$route);
  }
};
</script>

<style scoped>
.tags {
  position: relative;
  height: 40px;
  padding-top: 7px;
  overflow: hidden;
  background: #fff;
  padding-right: 120px;
  box-shadow:0 2px 5px 1px #eee;

}

.tags ul {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
}

.tags-li {
  float: left;
  margin: 3px 5px 2px 3px;
  border-radius: 3px;
  font-size: 12px;
  overflow: hidden;
  cursor: pointer;
  height: 23px;
  line-height: 23px;
  border: 1px solid #e9eaec;
  background: #fff;
  padding: 0 5px 0 12px;
  vertical-align: middle;
  color: #666;
  -webkit-transition: all 0.3s ease-in;
  -moz-transition: all 0.3s ease-in;
  transition: all 0.3s ease-in;
}

.tags-li.active {
  color: #fff;
  background-color: #42b983;
}

.tags-li-title {
  float: left;
  max-width: 80px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-right: 5px;
  color: #666;
}

.tags-li.active .tags-li-title {
  color: #fff;
}
</style>

